package com.logic.landseaserver.ws;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.logic.common.enums.HttpCodeEnum;
import com.logic.common.exception.BusinessException;
import com.logic.common.util.CommonResult;
import com.logic.common.util.CommonResultMap;
import com.logic.common.util.QueryUtil;
import com.logic.landseaserver.domain.Check;
import com.logic.landseaserver.domain.Issue;
import com.logic.landseaserver.service.ICheckService;
import com.logic.landseaserver.service.utils.ResetQueryUtil;
import com.logic.landseaserver.ws.dto.CheckDTO;
import com.logic.system.service.impl.CorporateService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Path("/check")
@Api(value="check")
public class CheckRest {
	@Autowired
	private ICheckService checkServiceImpl;

	private static final Logger logger = LoggerFactory.getLogger(CheckRest.class);

	@POST
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "Create a new check")
	public Response create(@ApiParam(value = "param", required = true) Check check) {
		CommonResultMap map = new CommonResultMap();
        try {
        	check.setSerialNum(System.currentTimeMillis() + "");
        	int id = checkServiceImpl.insert(check);
        	check.setId(id);
            map.setData(checkServiceImpl.getDTO(id));
            map.setResult(CommonResult.SUCCESS, "Create success");
        } catch (BusinessException e) {
        	logger.error("create check fail", e);
            map.setResult(e);
        } catch (Exception e) {
        	logger.error("create check fail", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}


	@DELETE
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "logic delete check by set deleted")
    public Response logicDelete(@ApiParam(value = "param", required = true) @QueryParam("checkId") String ids) {
        CommonResultMap map = new CommonResultMap();
        try {
        	checkServiceImpl.delete(ids);
            map.setResult(CommonResult.SUCCESS,"delete check");
        } catch (BusinessException e) {
        	logger.error("delete check fail", e);
            map.setResult(e);
        }  catch (Exception e) {
        	logger.error("delete check fail", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }

	@PUT
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "edit check ")
    public Response update(@ApiParam(value = "param", required = true) Check check) {
        CommonResultMap map = new CommonResultMap();
        try {
        	checkServiceImpl.update(check);
            map.setResult(CommonResult.SUCCESS,"edit check");
        } catch (BusinessException e) {
        	logger.error("edit check fail", e);
            map.setResult(e);
        }  catch (Exception e) {
        	logger.error("edit check fail", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }


    @GET
    @Path("/detail/{checkId}")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Get check by check id")
    public Response retrieveDTO(
            @ApiParam(value = "param", required = true) @PathParam("checkId") Integer checkId) {
        CommonResultMap map = new CommonResultMap();
        try {
            map.setData(checkServiceImpl.getDTO(checkId));
            map.setResult(CommonResult.SUCCESS);
        } catch (Exception e) {
            logger.error("get check detail by checkId  fail", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }


	@POST
	@Path("/detail/list")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "list checks")
	public Response listDTO(@ApiParam(value = "param", required = true) QueryUtil queryUtil){
        CommonResultMap map = new CommonResultMap();
        List<CheckDTO> checkList = null;
        try {
            queryUtil.getPagingTool().calculateStartIndex();
            ResetQueryUtil.reset(queryUtil);
            checkList = checkServiceImpl.queryDTO(queryUtil);
            Integer totalCount = queryUtil.getPagingTool().getTotalNum();
            map.setData(checkList);
            map.setResultTotalCount(totalCount);
            map.setResult(CommonResult.SUCCESS);

        } catch (Exception e) {
        	logger.error("get check list fail", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}


	@POST
	@Path("/{checkId}/issue")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "add issue to check")
	public Response addIssue(@ApiParam(value = "param", required = true) @PathParam("checkId") Integer checkId,
			@ApiParam(value = "param", required = true) Issue newIssue) {
		CommonResultMap map = new CommonResultMap();
        try {
        	newIssue.setSerialNum(System.currentTimeMillis() + "");
        	Issue issue = checkServiceImpl.addIssue(checkId, newIssue);
            map.setData(issue);
            map.setResult(CommonResult.SUCCESS, "add success");
        } catch (BusinessException e) {
        	logger.error("add issue to check fail", e);
            map.setResult(e);
        }  catch (Exception e) {
        	logger.error("add issue to check fail", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}

	@PUT
	@Path("/{checkId}/issue/batch")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "choose issue to check")
	public Response batchChooseIssue(@ApiParam(value = "param", required = true) @PathParam("checkId") Integer checkId,
		      @ApiParam(value = "param", required = true) @QueryParam("issueIds") String issueIds) {
		CommonResultMap map = new CommonResultMap();
        try {
        	checkServiceImpl.addIssue(checkId, issueIds);
            map.setResult(CommonResult.SUCCESS, "update success");
        } catch (BusinessException e) {
        	logger.error("batch add issue to check fail", e);
            map.setResult(e);
        }  catch (Exception e) {
        	logger.error("batch add issue to check fail", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}

	@DELETE
	@Path("/{checkId}/issue/batch")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "add issue to check")
	public Response batchRemoveIssue(@ApiParam(value = "param", required = true) @PathParam("checkId") Integer checkId,
		      @ApiParam(value = "param", required = true) @QueryParam("issueIds") String issueIds) {
		CommonResultMap map = new CommonResultMap();
        try {
        	checkServiceImpl.removeIssue(checkId, issueIds);
            map.setResult(CommonResult.SUCCESS, "delete success");
        } catch (Exception e) {
        	logger.error("batch delete issues fail", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}

	@POST
	@Path("/{checkId}/issues/batch")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "add issues to check")
	public Response batchAdddIssue(@ApiParam(value = "param", required = true) @PathParam("checkId") Integer checkId,
			@ApiParam(value = "param", required = true) List<Issue> newIssue) {
		CommonResultMap map = new CommonResultMap();
        try {
        	checkServiceImpl.batchAddIssue(checkId, newIssue);
            map.setResult(CommonResult.SUCCESS, "add success");
        } catch (BusinessException e) {
        	logger.error("batch add issues fail", e);
            map.setResult(e);
        }  catch (Exception e) {
        	logger.error("batch add issues fail", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}

	@POST
	@Path("/copy/{checkId}")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "Create a new check from template")
	public Response copy(
		      @ApiParam(value = "param", required = true) @PathParam("checkId") Integer checkId) {
		CommonResultMap map = new CommonResultMap();
        try {
            map.setData(checkServiceImpl.copyFromTemplate(checkId));
            map.setResult(CommonResult.SUCCESS, "update success");
        } catch (BusinessException e) {
        	logger.error("copy issue fail", e);
            map.setResult(e);
        }  catch (Exception e) {
        	logger.error("copy issue fail", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}

}
